﻿// Ignacio Quijas
// http://connectedenterprise.wordpress.com
// Description: BizTalk 2010 functoid that extracts a xml part using XPath
// Last Modification Date: July 2012
//
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.BizTalk.BaseFunctoids;
using System.Reflection;
using System.Xml;

namespace BizTalk.MapperExtensions.RESTFunctoids
{
    [Serializable]
    public class XPathExtract : BaseFunctoid
    {
        public XPathExtract()
            : base()
        {
            //ID for this functoid
            this.ID = 10002;

            // resource assembly must be ProjectName.ResourceName if building with VS.Net
            SetupResourceAssembly("BizTalk.MapperExtensions.RESTFunctoids.RESTFunctoidsResources", Assembly.GetExecutingAssembly());

            //Setup the Name, ToolTip, Help Description, and the Bitmap for this functoid
            SetName("IDS_XPATHEXTRACTOR_NAME");
            SetTooltip("IDS_XPATHEXTRACTOR_TOOLTIP");
            SetDescription("IDS_XPATHEXTRACTOR_DESCRIPTION");
            SetBitmap("IDS_XPATHEXTRACTOR_BITMAP");

            //category for this functoid. This functoid goes under the String Functoid Tab in the
            this.Category = FunctoidCategory.None;

            // Set the limits for the number of input parameters. This example: 1 parameter
            this.SetMinParams(2);
            this.SetMaxParams(2);

            // Add one line of code as set out below for each input param. For multiple input params, each line would be identical.
            AddInputConnectionType(ConnectionType.All); //first input
            AddInputConnectionType(ConnectionType.All); //second input

            // The functoid output can go to any node type.
            this.OutputConnectionType = ConnectionType.All;

            // Set the function name that is to be called when invoking this functoid.
            // To test the map in Visual Studio, this functoid does not need to be in the GAC.
            // If using this functoid in a deployed BizTalk app. then it must be in the GAC
            SetExternalFunctionName(GetType().Assembly.FullName, GetType().FullName, "XPathExtractor");
        }

        /// <summary>
        /// The real operation to be executed by the functoid
        /// </summary>
        public string XPathExtractor(string message, string fieldXPathExpression)
        {
            string response = "";
            XmlDocument messageToEvaluate = new XmlDocument();

            try
            {
                if (message != "")
                {
                    messageToEvaluate.LoadXml(message);
                    response = messageToEvaluate.SelectSingleNode(fieldXPathExpression).InnerXml;
                }
            }
            catch (Exception ex)
            {
            }

            return response;
        }
    }
}
